package com.heng.groupchat.websocket;

import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
@Component
@ServerEndpoint("/websocket/{userId}")
public class WebSocket {

    private Session session;

    private String userId;

    private static final CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value="userId")String userId) {
        this.session = session;
        this.userId = userId;
        webSockets.add(this);
        sendAllMessage("{\"user\":\""+userId+"\"}");
    }

    @OnClose
    public void onClose() {
        webSockets.remove(this);
    }

    public void sendAllMessage(String message) {
        for(WebSocket webSocket : webSockets) {
            if(webSocket.session.isOpen()) {
                webSocket.session.getAsyncRemote().sendText(message);
            }
        }
    }

    public List<String> getAllUser() {
        List<String> users = new ArrayList<>();
        for(WebSocket webSocket : webSockets) {
            if(webSocket.session.isOpen()) {
                users.add(webSocket.userId);
            }
        }
        return users;
    }
}
